package servlet.wxpay;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;
import servlet.wxpay.sdk.MyConfig;
import servlet.wxpay.sdk.WXPay;

public class WxPayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private OrderService orderService = new OrderServiceImpl(); 
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			
			String orderNO = request.getParameter("orderNO");
			Order order = orderService.findByOrderNO(orderNO);
			
			MyConfig config = new MyConfig();
	        WXPay wxpay = new WXPay(config);
			
			Map<String, String> data = new HashMap<String, String>();
	        data.put("body", order.getBody());
	        data.put("out_trade_no", order.getOrderNO());
	        data.put("device_info", "WEB");
	        data.put("fee_type", "CNY");
	        
	        int total_fee = (int)(order.getAmount()*100);
	        
	        data.put("total_fee", total_fee+"");
	        data.put("spbill_create_ip", "123.12.12.123");
	        data.put("notify_url", config.getNotifyUrl());
	        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
	        data.put("product_id", "1");
            
	        Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
            
            if (resp.get("return_code").equals("SUCCESS") && resp.get("result_code").equals("SUCCESS")){
            	request.setAttribute("code_url", resp.get("code_url"));
            	request.setAttribute("orderNO", order.getOrderNO());
                request.getRequestDispatcher("showQRCode.jsp").forward(request, response);
            } else {
            	response.getWriter().print(resp.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
